/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arlib.floatingsearchviewdemo.slice;

import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchviewdemo.adapter.SearchResultsListAdapter;
import com.arlib.floatingsearchviewdemo.ResourceTable;
import com.arlib.floatingsearchviewdemo.data.ColorWrapper;
import com.arlib.floatingsearchviewdemo.utils.LogUtil;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.PositionLayout;
import ohos.global.resource.Element;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

/**
 * MainAbilitySlice main class
 */
public class MainAbilitySlice extends AbilitySlice {
    private static final String TAG = "MainAbilitySlice";

    private static final int SUGGESTION_COUNT = 5;

    private PositionLayout myLayout = new PositionLayout(this);

    private ComponentContainer rootContainer;

    private List<String> sColorSuggestions = new ArrayList<>(
            Arrays.asList("green", "blue", "pink", "purple", "brown", "gray", "Granny Smith Apple", "Indigo", "Periwinkle",
                    "Mahogany", "Maize", "Mahogany", "Outer Space", "Melon", "Yellow", "Orange", "Red", "Orchid"));

    private List<ColorWrapper> coloursNameList;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        ComponentContainer.LayoutConfig config = new ComponentContainer.LayoutConfig(
                ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
        myLayout.setLayoutConfig(config);
        Component rootContainerComponent = LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_ability_main, null, false);
        if (rootContainerComponent instanceof ComponentContainer) {
            rootContainer = (ComponentContainer) rootContainerComponent;
        }

        FloatingSearchView floatingSearchView = new FloatingSearchView(this, null, sColorSuggestions);

        try {
            String[] coloursArray = getElement().getStringArray();
            List<String> coloursList = Arrays.asList(coloursArray);
            coloursNameList = new ArrayList<>();
            ColorWrapper colorWrapper;
            if (!coloursList.isEmpty()) {
                for (String currentItem : coloursList) {
                    String color = currentItem.substring(0, currentItem.indexOf("+"));
                    String name = currentItem.substring(currentItem.indexOf("+") + 1, currentItem.lastIndexOf("+"));

                    colorWrapper = new ColorWrapper();
                    colorWrapper.setColor(color);
                    colorWrapper.setName(name);

                    coloursNameList.add(colorWrapper);
                }
            }
        } catch (IOException | NotExistException | WrongTypeException e) {
            LogUtil.error(TAG, "Exception occurred - " + e.getMessage());
        }
        FloatingSearchView.init(SUGGESTION_COUNT, new FloatingSearchView.OnSuggestionClickListener() {
            @Override
            public void onSuggestionClick(String alert) {
                int textlength = alert.length();
                ArrayList<ColorWrapper> tempArrayList = new ArrayList<>();
                for (ColorWrapper currentItem : coloursNameList) {
                    if (textlength <= coloursNameList.size()) {
                        if (currentItem.getName().toLowerCase(Locale.getDefault()).contains(alert.toLowerCase(Locale.getDefault()))) {
                            currentItem.setName(currentItem.getName());
                            currentItem.setColor(currentItem.getColor());
                            tempArrayList.add(currentItem);
                        }
                    }
                }

                Component searchResultListContainerComp = rootContainer.findComponentById(
                        ResourceTable.Id_search_reult_list);
                if (searchResultListContainerComp instanceof ListContainer) {
                    ListContainer searchResultListContainer = (ListContainer) searchResultListContainerComp;
                    SearchResultsListAdapter listItemProvider = new SearchResultsListAdapter(getContext(),
                            tempArrayList);
                    searchResultListContainer.setItemProvider(listItemProvider);
                }
            }
        });

        super.setUIContent(rootContainer);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private Element getElement() {
        Element element = null;
        try {
            element = getResourceManager().getElement(ResourceTable.Strarray_colours);
        } catch (IOException | NotExistException | WrongTypeException e) {
            LogUtil.error(TAG, "Exception occurred - " + e.getMessage());
        }
        return element;
    }
}